package com.grwx.omc.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grwx.omc.admin.dao.SysRoleMapper;
import com.grwx.omc.admin.entity.SysRole;
import com.grwx.omc.admin.service.ISysRoleService;
import com.grwx.omc.exception.BusinessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
        implements ISysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Override
    public IPage<SysRole> page(Page<SysRole> page, SysRole sysRole) {
        return sysRoleMapper.pageList(page, sysRole);
    }

    @Override
    public void addOrUpdate(SysRole sysRole) {
        // 字典类型编码唯一性校验
        uniqueCheck(sysRole);

        if (null == sysRole.getId()) {
            sysRole.preInsert();
            save(sysRole);
        } else {
            sysRole.preUpdate();
            updateById(sysRole);
        }
    }

    @Override
    public void del(Long[] ids) {
        removeByIds(Arrays.asList(ids));
    }

    /**
     * typeCode唯一校验
     * 规则：同一字典类型下，字典数据名称和编码不能重复
     * @param sysRole
     */
    private void uniqueCheck(SysRole sysRole) {
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(sysRole.getId())){
            wrapper.ne("id", sysRole.getId());
        }
        wrapper.eq("role_name", sysRole.getRoleName());
        List<SysRole> existSysRole = list(wrapper);
        if (!ObjectUtils.isEmpty(existSysRole)) {
            throw new BusinessException("omc.admin.role_name.E001");
        }
    }
//
//
//    @Override
//    public List<SysLookupType> listRootType() {
//        return list(new QueryWrapper<SysLookupType>()
//                .eq("parent_id", 0)
//                .orderByDesc("update_time"));
//    }
//
//
//    @Override
//    public void del(Long[] ids) {
//        // TODO: 2020/5/13 删除校验
//
//        // TODO: 2020/5/13 级联删除、校验

//    }
}
